package cn.cf.kxx;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.content.ComponentName;
import android.content.Context;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Arrays;

import cn.cf.kxx.data.DataSharedPreferences;
import cn.cf.kxx.fram.OnActivityInteractionListener;
import cn.cf.kxx.fram.OnFragmentInteractionListener;
import cn.cf.kxx.model.Device;
import cn.cf.kxx.model.dev.Hold;
import cn.cf.kxx.service.IMyAidlCallBack;
import cn.cf.kxx.service.ISerialAidlInterface;
import cn.cf.kxx.tools.Tools;

public class FertilizerActivity extends Fragment implements View.OnClickListener, OnFragmentInteractionListener, TextView.OnEditorActionListener {

    byte[] bytes;

    @Override
    public void onRefrashString(String type) {
    }

    @Override
    public void onRefrashValve(int status) {
        if(status == 1){
            valveStatus.setText("已打开");
        }else{
            valveStatus.setText("已关闭");
        }
    }

    DataSharedPreferences sharedPreferences;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sharedPreferences = DataSharedPreferences.getInstance();
    }

    @Override
    public void onRefrashValues(Object obj) {
        byte[] content = (byte[]) obj;
        if(!Arrays.equals(bytes,content)){
            bytes = content;

            stress.setText(String.valueOf(Tools.TwoByteParserLit(Arrays.copyOfRange(bytes,13,15))));
            flow.setText(String.valueOf(Tools.TwoByteParserLit(Arrays.copyOfRange(bytes,15,17))));

            byte di = bytes[19];
            //电机
            if(((di >> 1) & 1) == 0){
                fertilizerSw.setTag(null);
                fertilizerTxt.setText("肥泵已关闭");
                fertilizerSw.setImageResource(R.mipmap.pump_close);
                fertilizerStatus.setImageResource(R.mipmap.led_failure);
                fertilizerImage.clearAnimation();
            }else{
                fertilizerSw.setTag("pump");
                fertilizerTxt.setText("肥泵已启动");
                fertilizerSw.setImageResource(R.mipmap.pump_open);
                fertilizerStatus.setImageResource(R.mipmap.led_success);
                startAnimation(fertilizerImage);
            }
            if(((di >> 7) & 1) == 0){
                failureImage.setImageResource(R.mipmap.led_success);
            }else{
                failureImage.setImageResource(R.mipmap.led_failure);
            }

            if(((di >> 5) & 1) == 0){
                liquid.setText("0");
            }else if(((di >> 6) & 1) == 0){
                liquid.setText("1");
            }else{
                liquid.setText("0.5");
            }

        }
    }

    Button goHome;
    View contentView;

    TextView fertilizerTxt,flow,stress,valveStatus;

    EditText liquid,pipTopPressure,pipTopVelocity,pipBotPressure;

    Button valveSw;

    ImageView fertilizerSw,fertilizerImage,fertilizerStatus,failureImage;

    public static FertilizerActivity newInstance(Bundle args) {
        FertilizerActivity fragment = new FertilizerActivity();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(contentView == null){
            contentView = inflater.inflate(R.layout.activity_fertilizer,container,false);
            initView();
        }else{
            ViewGroup parent = (ViewGroup) contentView.getParent();
            if (parent != null) {
                parent.removeView(contentView);
            }
        }
        return contentView;
    }

    private void initView() {
        valveStatus = contentView.findViewById(R.id.valveStatus);
        liquid = contentView.findViewById(R.id.liquid);
        valveSw = contentView.findViewById(R.id.valveSw);
        valveSw.setOnClickListener(this);
        fertilizerImage = contentView.findViewById(R.id.fertilizerImage);
        failureImage = contentView.findViewById(R.id.failureImage);
        fertilizerStatus = contentView.findViewById(R.id.fertilizerStatus);
        fertilizerSw = contentView.findViewById(R.id.fertilizerSw);
        fertilizerSw.setOnClickListener(this);
        fertilizerTxt = contentView.findViewById(R.id.fertilizerTxt);
        flow = contentView.findViewById(R.id.flow);
        stress = contentView.findViewById(R.id.stress);
        goHome = contentView.findViewById(R.id.goHome);
        goHome.setOnClickListener(this);

        pipTopPressure = contentView.findViewById(R.id.pipTopPressure);
        pipTopPressure.setOnEditorActionListener(this);
        pipTopVelocity = contentView.findViewById(R.id.pipTopVelocity);
        pipTopVelocity.setOnEditorActionListener(this);
        pipBotPressure = contentView.findViewById(R.id.pipBotPressure);
        pipBotPressure.setOnEditorActionListener(this);
    }


    OnActivityInteractionListener onActivityInteractionListener;
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        onActivityInteractionListener = (OnActivityInteractionListener) context;
    }

    RotateAnimation rotateAnimation;

    private void startAnimation(ImageView imageView){
        // 创建一个RotateAnimation对象，并设置旋转的角度和持续时间
        if(rotateAnimation == null){
            rotateAnimation = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            rotateAnimation.setDuration(1000); // 设置动画持续时间为1秒
            rotateAnimation.setInterpolator(new LinearInterpolator()); // 设置线性插值器
            // 设置动画的重复次数，这里设置为无限循环
            rotateAnimation.setRepeatCount(Animation.INFINITE);
        }
        // 开始动画
        imageView.startAnimation(rotateAnimation);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.goHome){
            onActivityInteractionListener.bakeFragment();
        }else if(v.getId() == R.id.fertilizerSw){
            if(v.getTag() == null){
                fertilizerSw.setImageResource(R.mipmap.pump_open);
                v.setTag("fertilizer");
                onActivityInteractionListener.sendCommand(5,4,1,new byte[]{1});
                fertilizerTxt.setText("肥泵启动中...");
            }else{
                fertilizerSw.setImageResource(R.mipmap.pump_close);
                v.setTag(null);
                onActivityInteractionListener.sendCommand(5,4,1,new byte[]{0});
                fertilizerTxt.setText("肥泵关闭中...");
            }
        }else if(v.getId() == R.id.valveSw){
            if(v.getTag() == null){
                v.setTag("valve");
                valveSw.setText("关闭");
                valveStatus.setText("已打开");
                onActivityInteractionListener.sendCommand(5,6,1,new byte[]{1});
            }else{
                v.setTag(null);
                valveSw.setText("打开");
                valveStatus.setText("已关闭");
                onActivityInteractionListener.sendCommand(5,6,1,new byte[]{0});
            }
        }
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            // 用户点击了输入法的确认按钮
            Log.e("dong",v.getText().toString());
            Log.e("dong",v.getId()+"=");
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0); // 关闭输入法

            String value = v.getText().toString();
            String data = sharedPreferences.getDevice(getActivity());
            if(!TextUtils.isEmpty(data)){
                if(TextUtils.isEmpty(value)){
                    value = "0";
                }
                Device device = Tools.gson.fromJson(data,Device.class);
                if (v.getId() == R.id.pipTopPressure){
                    device.setPipTopPressure(value);
                }else if (v.getId() == R.id.pipTopVelocity){
                    device.setPipTopVelocity(value);
                }else if (v.getId() == R.id.pipBotPressure){
                    device.setPipBotPressure(value);
                }
                onActivityInteractionListener.setDevice(device);
            }
            return true;
        }
        return false;
    }
}